# -*- coding: utf_8 -*-
# @Time : 2021/8/9 0009 15:47
# @Author : lyw
# @Remark : 门禁公共接口
import logging
import random
from mxsoftpy import TreeDB
from mxsoftpy.exception import DBError
from superbsapi import DecryptString

from index import mini_cache


class PublicInterfaceDB(TreeDB):

    def get_data_origin(self, host):
        """获取启用的数据源"""
        # print(host)
        _, data_origin = self.open("Janitor", "data_origin", file="IOT").filter(host=host, state=1)

        if data_origin:
            data_info = self.open("Janitor", "data_origin\\%s" % data_origin[0], file="IOT").items()
            data_info["id"] = data_origin[0]
            if data_info.get("password"):
                data_info["password"] = DecryptString(data_info["password"])[1]
            return data_info
        return {}

    def get_origin_model(self, origin_id):
        """获取数据源的模板"""
        model_data = self.open("Janitor", "data_origin_conf\\%s" % origin_id, file="IOT").sub_items()
        return model_data

    def get_door(self, origin_id):
        _, data_origin = self.open("Janitor", "door", file="IOT").filter(origin_id=origin_id, is_del=0)
        print(data_origin)
        res_list = []
        for i in data_origin:
            data_info = self.open("Janitor", "door\\%s" % i, file="IOT").items()
            data_info["id"] = i
            res_list.append(data_info)
        return res_list

    def query_origin(self):
        return self.open("Janitor", "data_origin_conf", file="IOT").sub_keys()


class DataInsertDB(TreeDB):

    def create(self, **kwargs):
        """插入"""
        # return self.open("Janitor", kwargs["sub_key"], file="IOT").insert_key_items(
        #     [(k, v) for k, v in kwargs["insert_dict"].items()])
        sub_key = self.open("Janitor", kwargs["sub_key"], file="IOT").insert_sub_keys("")
        self.open("Janitor", kwargs["sub_key"] + "\\" + sub_key, file="IOT").insert_items(
            [(k, v) for k, v in kwargs["insert_dict"].items()])
        return sub_key

    def update(self, **kwargs):
        """更新"""

        return self.open("Janitor", "\\".join((kwargs["sub_key"], kwargs["double_key"])), file="IOT").insert_items(
            [(k, v) for k, v in kwargs["insert_dict"].items()])

    def query_data(self, **kwargs):
        """查找数据"""
        try:
            sub_key = kwargs.pop("sub_key")
            total, data_origin = self.open("Janitor", sub_key, file="IOT").filter(**kwargs)
            print(data_origin)
            if data_origin:
                data_info = self.open("Janitor", "%s\\%s" % (sub_key, data_origin[0]), file="IOT").items()
                return data_origin[0], data_info
        except DBError as e:
            logging.error(e)
        return None, {}

    def query_personnel_data(self, **kwargs):
        """
        查找人员信息
        @param kwargs:
        @return:
        """
        sub_key = kwargs.pop("sub_key")
        res_dict = mini_cache.get(sub_key, cite=True)
        if res_dict:

            total, data_origin = self.open("Janitor", sub_key, file="IOT").filter(**kwargs)
            res_dict = {}
            for code in data_origin:
                data_info = self.open("Janitor", "%s\\%s" % (sub_key, code), file="IOT").items(
                    ["serial_num", "door_id"])
                try:
                    if res_dict.get((data_info["serial_num"], data_info["door_id"])):
                        continue
                    res_dict["_".join((data_info["serial_num"], data_info["door_id"]))] = code
                except:
                    continue
            mini_cache.set(sub_key, res_dict, 60 * 5)

        return res_dict

    def query_user_list(self, **kwargs):

        _, data_origin = self.open("Janitor", "personnel", file="IOT").filter(**kwargs)
        print(data_origin)
        # res_list = []
        res_dict = {}
        for code in data_origin:
            data_info = self.open("Janitor", "%s\\%s" % ("personnel", code), file="IOT").items(["serial_num", "name"])
            res_dict[data_info["serial_num"]] = {"code": code, "name": data_info["name"]}
        return res_dict

    def query_door(self):
        """查找门禁"""
        _door = mini_cache.get("janitor_door")
        if not _door:
            _door = self.open("Janitor", "door", file="IOT").sub_keys()
            mini_cache.set("janitor_door", _door, self.random_int())

        return _door

    def query_personnel(self):
        """查找人员"""
        _personnel = mini_cache.get("janitor_personnel")
        if not _personnel:
            _personnel = self.open("Janitor", "personnel", file="IOT").sub_keys()
            mini_cache.set("janitor_personnel", _personnel, self.random_int())
        return _personnel

    def query_model(self):
        """查找设备模板"""
        door_list = self.open("Janitor", "data_origin_conf", file="IOT").sub_keys()
        return door_list

    def query_origin(self):
        """查找数据源"""
        door_list = self.open("Janitor", "data_origin", file="IOT").sub_keys()
        return door_list

    @staticmethod
    def random_int():
        "随机数字"
        return random.randint(20, 60) * random.randint(1, 3)
